<template>
    <div class="notification-list">
        <!-- Search form -->
        <el-form :inline="true" :model="query" class="demo-form-inline" size="small">
            <el-form-item label="通知标题">
                <el-input v-model="query.title" placeholder="请输入通知标题" clearable>
                    <template #prefix
                        ><el-icon class="el-input__icon"><Search /></el-icon
                    ></template>
                </el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="load">查询</el-button>
                <el-button type="danger" @click="clear">重置</el-button>
            </el-form-item>
        </el-form>

        <!-- Notification data table -->
        <el-table :data="notifications" stripe border v-loading="loading" :max-height="getTableHeight()">
            <el-table-column prop="id" label="通知编号" sortable width="100" />
            <el-table-column prop="title" label="通知标题" />
            <el-table-column prop="content" label="通知内容" />
            <el-table-column prop="userId" label="用户ID" width="100" />
            <el-table-column fixed="right" label="操作" width="150">
                <template #default="scope">
                    <!-- <el-button size="small" @click="openEditDialog(scope.row)">编辑</el-button> -->
                    <el-popconfirm title="确认删除?" @confirm="handleDelete(scope.row.id)">
                        <template #reference>
                            <el-button type="danger" size="small">删除</el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>

        <!-- Pagination -->
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[5, 10, 20, 50]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />

        <!-- Edit notification dialog -->
        <!-- <el-dialog v-model="editDialogVisible" title="编辑通知">
            <el-form :model="editForm" :rules="rules" ref="editFormRef" label-width="100px">
                <el-form-item label="通知标题" prop="title">
                    <el-input v-model="editForm.title" placeholder="请输入通知标题"></el-input>
                </el-form-item>
                <el-form-item label="通知内容" prop="content">
                    <el-input type="textarea" v-model="editForm.content" placeholder="请输入通知内容"></el-input>
                </el-form-item>
                <el-form-item label="用户ID" prop="userId">
                    <el-input v-model="editForm.userId" placeholder="请输入用户ID"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="editDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleEdit">确定</el-button>
                </span>
            </template>
        </el-dialog> -->
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';
import { Search } from '@element-plus/icons-vue';
import { getTableHeight } from '../utils/role';

const notifications = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const loading = ref(false);
const query = reactive({
    title: '',
});

const editDialogVisible = ref(false);
// const editForm = reactive({
//     id: '',
//     title: '',
//     content: '',
//     userId: '',
// });
// const editFormRef = ref(null);

// const rules = {
//     title: [{ required: true, message: '请输入通知标题', trigger: 'blur' }],
//     content: [{ required: true, message: '请输入通知内容', trigger: 'blur' }],
//     userId: [{ required: true, message: '请输入用户ID', trigger: 'blur' }],
// };

// 获取当前用户ID
const getCurrentUserId = () => {
    const user = JSON.parse(sessionStorage.getItem('user') || '{}');
    return user.id || null;
};

const currentUserId = getCurrentUserId();

// 筛选当前用户的通知
const filteredNotifications = computed(() => {
    return notifications.value.filter((notification) => notification.userId == currentUserId);
});

// 筛选后的通知总数
const filteredTotal = computed(() => {
    return filteredNotifications.value.length;
});

const load = async () => {
    loading.value = true;
    try {
        let userStr = sessionStorage.getItem('user') || '{}';
        const { role, id } = JSON.parse(userStr);
        const params = {
            title: query.title,
            pageNum: currentPage.value,
            pageSize: pageSize.value,
        };
        if ([3, 4, 5].includes(role)) {
            params.role = role;
        } else if (role === 2) {
            params.userId = id;
        }
        const response = await axios.get('http://localhost:8080/api/tongzhi/search', { params });
        if (response.data.status === 200) {
            notifications.value = response.data.data.records;
            total.value = response.data.data.total;
        } else {
            ElMessage.error('获取通知信息失败');
        }
    } catch (error) {
        ElMessage.error('请求通知信息出错: ' + error.message);
    } finally {
        loading.value = false;
    }
};

const clear = () => {
    Object.keys(query).forEach((key) => (query[key] = ''));
    currentPage.value = 1;
    load();
};

const handleDelete = async (id) => {
    try {
        await axios.delete(`http://localhost:8080/api/tongzhi/delete/${id}`);
        ElMessage.success('删除成功');
        load();
    } catch (error) {
        ElMessage.error('删除失败: ' + error.message);
    }
};

// const openEditDialog = (notification) => {
//     Object.assign(editForm, notification);
//     editDialogVisible.value = true;
// };

// const handleEdit = async () => {
//     editFormRef.value.validate(async (valid) => {
//         if (valid) {
//             try {
//                 await axios.put('http://localhost:8080/api/tongzhi/update', editForm);
//                 ElMessage.success('编辑成功');
//                 editDialogVisible.value = false;
//                 load();
//             } catch (error) {
//                 ElMessage.error('编辑失败: ' + error.message);
//             }
//         }
//     });
// };

const handleSizeChange = (newSize) => {
    pageSize.value = newSize;
    load();
};

const handleCurrentChange = (newPage) => {
    currentPage.value = newPage;
    load();
};

onMounted(() => {
    load();
});
</script>

<style scoped>
.notification-list {
    padding: 20px;
}

.el-pagination {
    margin-top: 20px;
    justify-content: center;
}
</style>
